<?php
/**
*
*
*
*/
use Yz_Log_Log as Log;

class Yz_Exception extends Exception {

    protected $originalMessage;

    protected $values = array();

    protected $defaultMessage = "General exception";
    /**
    *   A handler may get parameters from
    *
    *   To ensure that messages may be safely localized
    *
    * @param string message: the message as above
    * @param int code: a code from list
    * @param Exception previous -> compatibility with 'Exception'
    *
    */
    public function __construct( $message=null, $code=null, $previous=null )
    {

        $code or $code = Log::CRITICAL;

        $message or $message = $this->defaultMessage;

        parent::__construct( $message, $code, null );

        Log::log( sprintf( "%s at %s[%s]: %s",
                       get_class($this),
                       $this->file,
                       $this->line,
                       $this->message
              ),
              $code
        );
    } // __construct


    /**
    *
    */
    public function __toString()
    {
        try {
            $o = $this->toString();
        } catch (Exception $ex) {
            debug("toString Exception: ".$ex->getTraceAsString());
            $o = "Exception "
                . get_class($this)
                . ": "
                . $this->getFile()
                . ": "
                . $this->getLine()
                . ": "
                . $this->getMessage();
        }
        return $o;
    }


    /**
    *
    *
    */
    public function toString( $full=false )
    {
        if ( null === $this->originalMessage ) {
            $this->originalMessage = $this->message;

            if ( $this->values ) {
                $this->message = Yz_String::replaceVars( $this->message, new ArrayObject($this->values) );
            }
        }

        $str = get_class( $this ) . "($this->file:$this->line): $this->message";

        if ( $full ) {
            $str .= "\nStack trace:\n" . $this->getTraceAsString();
        }

        return $str;
    } // toString



    /**
    *
    *
    */
    public function toLocaleString()
    {
        $msg = $this->originalMessage ?: $this->message;
        return I18N::tp($msg, new Yz_Hash($this->values));

        //TODO: take domain from ClassName|property
        $localeMsg = I18N::dsm( 'Yz', 'exceptions', $msg );

        if ( null === $localeMsg ) {
            $localeMsg = $msg;
        }
        $msg = Yz_String::replaceVars( $localeMsg, new ArrayObject($this->values) );

        return $msg;
    } // toLocaleString



    /**
    *
    *
    */
    public function withArgs( array $args )
    {
        $this->values = $args;

        return $this;
    } // withArgs


} // class Yz_Exception

